package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.OnlineStatus;
import com.ruoyi.common.exception.IAMException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.auth.CustomizedToken;
import com.ruoyi.framework.shiro.enums.LoginType;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.shiro.session.OnlineSession;
import com.ruoyi.framework.shiro.session.OnlineSessionDAO;
import com.ruoyi.framework.shiro.util.ApiEncryptUtils;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    /**
     * 是否开启记住我功能
     */
    @Value("${shiro.rememberMe.enabled: false}")
    private boolean rememberMe;

    @Autowired
    private ConfigService configService;

    @Autowired
    private ISysAuthService authService;

    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private OnlineSessionDAO onlineSessionDAO;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysThirdService thirdService;

    @Autowired
    private ISysAppService appService;

    @Autowired
    private ISysATrustCodeService aTrustCodeService;


    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        // 是否开启用户注册
        mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe, Boolean proxy,
                                String appId, String responseType, String state, String redirectUrl) {
        CustomizedToken token = new CustomizedToken(username, password, rememberMe, proxy, LoginType.PASSWORD);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);

            if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(redirectUrl)) {
                SysApp sysApp = appService.selectAppByClientId(appId);
                if (sysApp == null) {
                    return error("APPID 不存在");
                }

                if (!StringUtils.equals(responseType, "code")) {
                    return error("responseType仅支持code");
                }

                String code = IdUtil.simpleUUID();
                SysUser sysUser = ShiroUtils.getSysUser();
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(redirectUrl);
                builder.queryParam("code", code);
                if (StringUtils.isNotEmpty(state)) {
                    builder.queryParam("state", state);
                }

                SysATrustCode sysAtrustCode = new SysATrustCode();
                sysAtrustCode.setCode(code);
                sysAtrustCode.setUserId(sysUser.getUserId());
                sysAtrustCode.setExpireTime(DateUtil.offsetMinute(DateUtil.date(), 5));
                aTrustCodeService.insertCode(sysAtrustCode);
                return success((Object) builder.toUriString());
            }

            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }

    @GetMapping("/enabledAuthWays")
    @ResponseBody
    public AjaxResult enabledAuthWays() {
        List<SysAuth> res = authService.getEnabledAuthWay();
        return success(res);
    }

    @PostMapping("/singleLogout")
    @ResponseBody
    public AjaxResult singleLogout(String logoutRequest) {
        String st = getSt(logoutRequest);
        log.info("单点登出被调用，st: {}", st);
        SysUserOnline online = userOnlineService.selectOnlineBySt(st);
        if (online == null) {
            log.warn("单点登出：用户已下线");
            return error("用户已下线");
        }
        OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
        if (onlineSession == null) {
            log.warn("单点登出：用户已下线");
            return error("用户已下线");
        }

        onlineSessionDAO.delete(onlineSession);
        online.setStatus(OnlineStatus.off_line);
        userOnlineService.saveOnline(online);
        userOnlineService.removeUserCache(online.getLoginName(), online.getSessionId());

        log.info("单点登出已完成");
        return success();
    }

    @PostMapping("/checkPwd")
    @ResponseBody
    public Map<String, Object> checkPwd(@RequestBody String param) {
        SysThird third = thirdService.selectThirdAuth();
        String secret = third.getApiKey();

        String encType = third.getApiEnc();
        String data = ApiEncryptUtils.decrypt(param, secret, encType);

        if (data == null) {
            throw new IAMException("数据解密失败");
        }

        Map<String, String> paramMap = JSONUtil.toBean(data, new TypeReference<>() {
        }, true);

        String account = paramMap.get("account");
        String password = paramMap.get("password");

        if (StringUtils.isAnyBlank(account, password)) {
            throw new IAMException("账号或密码不能为空");
        }

        SysUser user = userService.selectUserByLoginName(account);
        if (user == null) {
            throw new IAMException("账号不存在");
        }

        boolean matches = passwordService.matches(user, password);
        if (!matches) {
            throw new IAMException("账号或密码错误");
        }

        log.info("账号[{}]认证成功", account);
        return Map.of("code", 0, "result", true);
    }

    public String getSt(String logoutRequest) {
        String reg = ".*?<samlp:SessionIndex>(.*?)</samlp:SessionIndex>.*";
        return logoutRequest.replaceAll(reg, "$1");
    }
}
